package com.media.system.controller;

import com.media.system.common.core.controller.BaseController;
import com.media.system.common.core.domain.AjaxResult;
import com.media.system.domain.MediaFile;
import com.media.system.service.AiTagService;
import com.media.system.service.MediaFileService;
import com.media.system.service.dto.AiTagResult;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * AI智能标签控制器
 * 
 * @author Claude
 * @since 2024-01-20
 */
@RestController
@RequestMapping("/ai/tags")
@Tag(name = "AI智能标签", description = "AI标签识别、智能分类等功能")
@Slf4j
public class AiTagController extends BaseController {

    @Autowired
    private AiTagService aiTagService;

    @Autowired
    private MediaFileService mediaFileService;

    /**
     * 手动触发单个文件的AI标签识别
     */
    @PostMapping("/recognize/{fileId}")
    @PreAuthorize("hasPermission('ai:tag:recognize')")
    @Operation(summary = "AI标签识别", description = "对指定文件进行AI标签识别")
    public AjaxResult recognizeFileTags(
            @Parameter(description = "文件ID", required = true) @PathVariable("fileId") Long fileId) {
        
        try {
            MediaFile mediaFile = mediaFileService.getById(fileId);
            if (mediaFile == null) {
                return error("文件不存在");
            }
            
            // 验证文件所有权
            if (!mediaFile.getUserId().equals(getUserId())) {
                return error("无权限访问该文件");
            }
            
            AiTagResult result;
            switch (mediaFile.getFileType().toLowerCase()) {
                case "image":
                    result = aiTagService.recognizeImageTags(mediaFile);
                    break;
                case "video":
                    result = aiTagService.recognizeVideoTags(mediaFile);
                    break;
                case "audio":
                    result = aiTagService.recognizeAudioTags(mediaFile);
                    break;
                default:
                    return error("不支持的文件类型");
            }
            
            // 更新文件的AI标签
            if ("success".equals(result.getStatus()) && result.getTags() != null) {
                String aiTags = result.getTags().stream()
                        .map(AiTagResult.AiTag::getName)
                        .reduce((a, b) -> a + "," + b)
                        .orElse("");
                mediaFileService.updateAiTags(fileId, aiTags);
            }
            
            return success("AI标签识别完成", result);
            
        } catch (Exception e) {
            log.error("AI标签识别失败: {}", e.getMessage(), e);
            return error("AI标签识别失败: " + e.getMessage());
        }
    }

    /**
     * 批量AI标签识别
     */
    @PostMapping("/batch-recognize")
    @PreAuthorize("hasPermission('ai:tag:recognize')")
    @Operation(summary = "批量AI标签识别", description = "批量对多个文件进行AI标签识别")
    public AjaxResult batchRecognizeTags(
            @Parameter(description = "文件ID列表", required = true) @RequestBody List<Long> fileIds) {
        
        try {
            List<MediaFile> mediaFiles = fileIds.stream()
                    .map(mediaFileService::getById)
                    .filter(file -> file != null && file.getUserId().equals(getUserId()))
                    .toList();
            
            if (mediaFiles.isEmpty()) {
                return error("没有有效的文件");
            }
            
            // 异步批量处理
            List<AiTagResult> results = aiTagService.batchRecognizeTags(mediaFiles);
            
            // 更新成功识别的文件标签
            for (AiTagResult result : results) {
                if ("success".equals(result.getStatus()) && result.getTags() != null) {
                    String aiTags = result.getTags().stream()
                            .map(AiTagResult.AiTag::getName)
                            .reduce((a, b) -> a + "," + b)
                            .orElse("");
                    mediaFileService.updateAiTags(result.getFileId(), aiTags);
                }
            }
            
            return success("批量AI标签识别已开始", results);
            
        } catch (Exception e) {
            log.error("批量AI标签识别失败: {}", e.getMessage(), e);
            return error("批量AI标签识别失败: " + e.getMessage());
        }
    }

    /**
     * 获取推荐标签
     */
    @GetMapping("/recommended")
    @PreAuthorize("hasPermission('ai:tag:view')")
    @Operation(summary = "获取推荐标签", description = "基于用户历史获取推荐标签")
    public AjaxResult getRecommendedTags(
            @Parameter(description = "文件类型") @RequestParam(value = "fileType", required = false) String fileType) {
        
        try {
            List<String> tags = aiTagService.getRecommendedTags(getUserId(), fileType);
            return success(tags);
        } catch (Exception e) {
            log.error("获取推荐标签失败: {}", e.getMessage(), e);
            return error("获取推荐标签失败");
        }
    }

    /**
     * 获取热门标签
     */
    @GetMapping("/popular")
    @Operation(summary = "获取热门标签", description = "获取系统热门标签")
    public AjaxResult getPopularTags(
            @Parameter(description = "数量限制") @RequestParam(value = "limit", defaultValue = "20") Integer limit) {
        
        try {
            List<String> tags = aiTagService.getPopularTags(limit);
            return success(tags);
        } catch (Exception e) {
            log.error("获取热门标签失败: {}", e.getMessage(), e);
            return error("获取热门标签失败");
        }
    }

    /**
     * 智能分类到相册
     */
    @PostMapping("/classify")
    @PreAuthorize("hasPermission('ai:tag:classify')")
    @Operation(summary = "智能分类", description = "基于AI标签智能分类文件到相册")
    public AjaxResult smartClassify(
            @Parameter(description = "文件ID列表", required = true) @RequestBody List<Long> fileIds) {
        
        try {
            List<MediaFile> mediaFiles = fileIds.stream()
                    .map(mediaFileService::getById)
                    .filter(file -> file != null && file.getUserId().equals(getUserId()))
                    .toList();
            
            if (mediaFiles.isEmpty()) {
                return error("没有有效的文件");
            }
            
            List<String> albums = aiTagService.smartClassifyToAlbums(mediaFiles);
            return success("智能分类完成", albums);
            
        } catch (Exception e) {
            log.error("智能分类失败: {}", e.getMessage(), e);
            return error("智能分类失败: " + e.getMessage());
        }
    }

    /**
     * 相似文件检测
     */
    @GetMapping("/similar/{fileId}")
    @PreAuthorize("hasPermission('ai:tag:view')")
    @Operation(summary = "相似文件检测", description = "检测与指定文件相似的其他文件")
    public AjaxResult detectSimilarFiles(
            @Parameter(description = "文件ID", required = true) @PathVariable("fileId") Long fileId) {
        
        try {
            MediaFile mediaFile = mediaFileService.getById(fileId);
            if (mediaFile == null || !mediaFile.getUserId().equals(getUserId())) {
                return error("文件不存在或无权限访问");
            }
            
            List<MediaFile> similarFiles = aiTagService.detectSimilarFiles(mediaFile);
            return success(similarFiles);
            
        } catch (Exception e) {
            log.error("相似文件检测失败: {}", e.getMessage(), e);
            return error("相似文件检测失败");
        }
    }

    /**
     * 内容安全检测
     */
    @PostMapping("/safety-check/{fileId}")
    @PreAuthorize("hasPermission('ai:tag:safety')")
    @Operation(summary = "内容安全检测", description = "对文件进行内容安全检测")
    public AjaxResult contentSafetyCheck(
            @Parameter(description = "文件ID", required = true) @PathVariable("fileId") Long fileId) {
        
        try {
            MediaFile mediaFile = mediaFileService.getById(fileId);
            if (mediaFile == null || !mediaFile.getUserId().equals(getUserId())) {
                return error("文件不存在或无权限访问");
            }
            
            boolean isSafe = aiTagService.contentSafetyCheck(mediaFile);
            return success("安全检测完成", Map.of("isSafe", isSafe));
            
        } catch (Exception e) {
            log.error("内容安全检测失败: {}", e.getMessage(), e);
            return error("内容安全检测失败");
        }
    }

    /**
     * 获取AI处理统计
     */
    @GetMapping("/statistics")
    @PreAuthorize("hasPermission('ai:tag:view')")
    @Operation(summary = "AI处理统计", description = "获取用户的AI处理统计信息")
    public AjaxResult getAiStatistics() {
        try {
            // 模拟统计数据
            Map<String, Object> statistics = Map.of(
                "totalProcessed", 156,
                "imagesProcessed", 120,
                "videosProcessed", 25,
                "audiosProcessed", 11,
                "averageProcessingTime", 2.5,
                "topTags", Arrays.asList("家庭", "旅行", "美食", "风景", "人物"),
                "monthlyTrend", Arrays.asList(45, 52, 38, 61, 73, 68, 82)
            );
            
            return success(statistics);
        } catch (Exception e) {
            log.error("获取AI统计失败: {}", e.getMessage(), e);
            return error("获取AI统计失败");
        }
    }
}